package com.djk.daily.thread.stopthreads;

/**
 * @author dujunkai
 * @version 1.0
 * @description: 如果在执行过程中，每次循环都会调用sleep或wait等方法，那么不需要每次迭代都检查是否已中断
 * @date 2021/7/2 16:06
 */
public class RightWayStopThreadWithSleepEveryLoop {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            int num = 0;
            try {
                while (num <= 10000) {
                    if (num % 100 == 0) {
                        System.out.println("当前时间：" + System.currentTimeMillis() + "  " +num + "是100的倍数");
                    }
                    num++;
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                System.out.println("当前时间：" + System.currentTimeMillis() + "  线程" + Thread.currentThread().getName() + "中断异常，此时num = " + num);
                e.printStackTrace();
            }
        };

        Thread thread = new Thread(runnable);
        thread.start();
        System.out.println("当前时间：" + System.currentTimeMillis() + "  主线程" + Thread.currentThread().getName() + "休眠5秒钟");
        Thread.sleep(5000);
        System.out.println("当前时间：" + System.currentTimeMillis() + "  主线程" + Thread.currentThread().getName() + "休眠结束，开始通知线程" + thread.getName() + "中断");
        thread.interrupt();
    }
}
